<template>
  <div>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;padding-bottom: 0px;
    display: flex;justify-content: space-between">
      <el-form :inline="true">
        <el-form-item prop="userId">
          <el-input
          v-model="select.crypto"
            :placeholder="$t('iptdefault.iptIcon')"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getstakingSubmit">{{$t('publicbtn.query')}}</el-button>
        </el-form-item>

         <el-form-item>
          <el-button type="primary" @click="getnewlyadded">{{$t('publicbtn.newlyadded')}}</el-button>
        </el-form-item>

           <el-form-item>
          <el-button type="primary" @click="getstakingRefresh">{{$t('publicbtn.refresh')}}</el-button>
        </el-form-item>
      </el-form>

      <el-form :inline="true" style="display:flex;align-item:center;">
        <el-form-item>
          <el-upload
            class="upload-demo"
            action=""
            :on-change="handleChange"
            :show-file-list="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false">
            <el-button size="primary" type="primary" >{{$t('publicbtn.impotr')}}</el-button>
        </el-upload>
          </el-form-item>
        <excelexport></excelexport>
      </el-form>



    </el-col>
    <el-table
      v-loading="loading"
      :data="stakingListdata"
      style="width: 100%"
      id="out-table"
    >
      <el-table-column prop="name" :label="$t('field.nametw')" width="230" fixed="left"></el-table-column>
      <el-table-column prop="crypto" label="Coin" width="230"></el-table-column>
      <el-table-column prop="type" :label="$t('stakinglist.type')" width="230">
         <template slot-scope="props">
           {{
            props.row.type ==1?$t('stakinglist.current'):props.row.type ==2?$t('stakinglist.regular'):''
           }}
         </template>
      </el-table-column>
      <el-table-column prop="rate" :label="$t('stakinglist.interestrate')" width="230"> </el-table-column>
      <el-table-column prop="sort" :label="$t('field.sort')" width="230"> </el-table-column>
      <el-table-column prop="cycle" :label="$t('stakinglist.payoutperiod')" width="230"> </el-table-column>
      <el-table-column prop="lockDay" :label="$t('stakinglist.nvestmentperiod')"  width="230"> </el-table-column>
      <el-table-column prop="unlockDay" :label="$t('stakinglist.unlockingperiod')" width="230"></el-table-column>
      <el-table-column prop="descTc"  :label="$t('stakinglist.traditionalchinese')" width="230"></el-table-column>
      <el-table-column prop="descZh"  :label="$t('stakinglist.simplifieddescription')" width="230"></el-table-column>
      <el-table-column prop="descEn" :label="$t('stakinglist.explanationinEnglish')" width="230"></el-table-column>
      <el-table-column prop="minTime" :label="$t('stakinglist.minimumpledge')" width="230"></el-table-column>
      <el-table-column prop="maxTime" :label="$t('stakinglist.maximumpledge')" width="230"></el-table-column>
      <el-table-column prop="maxAll" :label="$t('stakinglist.pledgeatmost')" width="230"></el-table-column>
       <el-table-column :label="$t('field.operation')" width="180" fixed="right" >
                <template slot-scope="props">
                  <el-button
                    size="mini"
                    @click="updatastking(props.row)">
                    {{$t('publicbtn.modifyinformation')}}
                  </el-button>

                    <el-button 
            size="mini"
            type="primary"
            @click="delectStkingbtn(props.row.id)"
          >      {{$t('publicbtn.delete')}}

          </el-button>
                </template>
                </el-table-column>
    </el-table>


	  <!--新增||修改userUpdateMoney -->
    <div class="userUpdateMoney" v-if='getnewlyadd'>
      <div class="userUpdateForm">
        <h2>{{upnewtitle}}</h2>
          <el-form
          :model="getupdatanewdata"
          :rules='rules'
          ref="getupdatanewdata"
          label-width="100px"
          class="demo-updateForm">

          <div style="display: flex">

            <div class="updateLeft">
              <el-form-item label-width="140px" :label="$t('field.nametw')" prop="name">
                <el-input
                  v-model="getupdatanewdata.name"
                  :placeholder="$t('stakinglist.iptnametw')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" label="Coin" prop="crypto">
                <el-input
                  v-model="getupdatanewdata.crypto"
                  :placeholder="$t('stakinglist.iptcoin')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.type')"  prop="type">
                <el-select @change = 'changeType'
                  v-model="getupdatanewdata.type"
                        :placeholder="$t('stakinglist.iptcurrent')">
                  <el-option :label="$t('stakinglist.current')" :value="1"></el-option>
                  <el-option :label="$t('stakinglist.regular')" :value="2"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.interestrate')" prop="rate">
                <el-input
                  v-model="getupdatanewdata.rate" 
                  :placeholder="$t('stakinglist.iptinterestrate')"   
                ></el-input>
              </el-form-item>

                <el-form-item label-width="140px" :label="$t('field.sort')" prop="sort">
                <!-- onkeyup="this.value=this.value.replace(/\D/g,'')" -->
                <el-input 
                  v-model="getupdatanewdata.sort" 
                  :placeholder="$t('field.inputsort')"
                ></el-input>
                <!-- <el-input-number v-model="getupdatanewdata.sort" :min=1 :step=1 :precision=0></el-input-number> -->
              </el-form-item>

                  <el-form-item label-width="140px" :label="$t('stakinglist.payoutperiod')" prop="cycle">
                <el-input
                   v-model="getupdatanewdata.cycle" 
                  :placeholder="$t('stakinglist.iptpayoutperiod')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.nvestmentperiod')" prop="lockDay">
                <el-input
                  v-model="getupdatanewdata.lockDay"
                  :placeholder="$t('stakinglist.iptnvestmentperiod')"
                  :disabled="disabled.disabledhouqi"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.unlockingperiod')" prop="unlockDay">
                <el-input
                  v-model="getupdatanewdata.unlockDay"
                  :placeholder="$t('stakinglist.iptunlockingperiod')"
                  :disabled="disabled.disabledsiqi"

                ></el-input>
              </el-form-item>

            

              </div>

                <div class="updateright">
              <el-form-item label-width="140px" :label="$t('stakinglist.traditionalchinese')" prop="descTc">
                <el-input
                  v-model="getupdatanewdata.descTc"
                  :placeholder="$t('stakinglist.ipttraditionalchinese')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.simplifieddescription')" prop="descZh">
                <el-input
                  v-model="getupdatanewdata.descZh"
                  :placeholder="$t('stakinglist.iptsimplifieddescription')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.explanationinEnglish')" prop="descEn">
                <el-input
                  v-model="getupdatanewdata.descEn"
                  :placeholder="$t('stakinglist.iptexplanationinEnglish')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.minimumpledge')" prop="minTime">
                <!-- onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" -->
                <el-input
                  v-model="getupdatanewdata.minTime" 
                  :placeholder="$t('stakinglist.iptminimumpledge')"
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.maximumpledge')" prop="maxTime">
                <el-input
                  v-model="getupdatanewdata.maxTime" 
                  :placeholder="$t('stakinglist.iptmaximumpledge')" 
                ></el-input>
              </el-form-item>

              <el-form-item label-width="140px" :label="$t('stakinglist.pledgeatmost')" prop="maxAll">
                <el-input
                  v-model="getupdatanewdata.maxAll"
                  :placeholder="$t('stakinglist.iptpledgeatmost')"
                ></el-input>
              </el-form-item>
   
              </div>
           
          </div>

          <el-form-item style="text-align: center">
            <el-button type="primary" @click="usernewupSubmit('getupdatanewdata')"
              >{{$t('publicbtn.updatenow')}}</el-button>
            <el-button @click="usernewupSubmitReset">{{$t('publicbtn.cancel')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Cryptojs from 'crypto-js'
import excelexport from '@/components/export.vue'
import {postUserRequest, getUserRequest,getNudataRequest } from "@/api/api";
export default {
name:'stakinglist',
components:{
excelexport
},

data(){
  return{
  upnewtitle:'',
  loading:true,
  stakingListdata:null,
  getnewlyadd:false,
  getnewlyaddapi:false,
  getnuplyaddapi:false,
  getupdatanewdata:{},
//   rules:{
//     name:{ required: true, message: '请输入名称', trigger: 'blur' },
//     crypto:{ required: true, message: '请输入Coin', trigger: 'blur' },
//     type:{ required: true, message: '请选择类型', trigger: 'blur' },
//     rate:{ required: true, message: '请输入年利率', trigger: 'blur' },
//     sort:{ required: true, message: '请输入排序', trigger: 'blur' },
//     lockDay:{ required: true, message: '请输入投资期(天)', trigger: 'blur' },
//     unlockDay:{ required: true, message: '请输入解锁期(天)', trigger: 'blur' },
//     cycle:{ required: true, message: '请输入派息周期(分钟)', trigger: 'blur' },
//     descTc:{ required: false, message: '请输入说明 繁体', trigger: 'blur' },
//     descZh:{ required: false, message: '请输入说明 简体', trigger: 'blur' },
//     descEn:{ required: false, message: '请输入说明 英文', trigger: 'blur' },
//     minTime:{ required: true, message: '请输入单次最小质押', trigger: 'blur' },
//     maxTime:{ required: true, message: '请输入单次最大质押', trigger: 'blur' },
//     maxAll:{ required: true, message: '请输入每人最多可以质押', trigger: 'blur' },
//  },
 select:{
   crypto:null
 },
 disabled:{
   disabledhouqi:true,
   disabledsiqi:true
 }
  }
},
computed:{
  rules:function(){
return{
    name: {required: true, message: this.$t('stakinglist.iptnametw'), trigger: 'blur' },
    crypto:{ required: true, message: this.$t('stakinglist.iptcoin'), trigger: 'blur' },
    type:{ required: true, message:  this.$t('stakinglist.iptcurrent'), trigger: 'blur' },
    rate:{ required: true,
     pattern:/^\d+(\.\d+)?$/,
     message: this.$t('stakinglist.iptinterestrate'), trigger: 'blur'
      },
    sort:[{ 
      required: true,pattern:/^\+?[0-9]\d*$/, message:  this.$t('field.inputsort'), trigger: 'blur'
       }],
    lockDay:{ required: false, pattern: /^\d+(\.\d+)?$/, message: this.$t('stakinglist.iptnvestmentperiod'), trigger: 'blur' },
    unlockDay:{ required: false,pattern: /^\d+(\.\d+)?$/, message: this.$t('stakinglist.iptunlockingperiod'), trigger: 'blur' },
    cycle:[
     {required: true, pattern: /^[0-9]+$/, message: this.$t('stakinglist.iptpayoutperiod') ,trigger: 'blur'}
    ],
    descTc:{ required: false, message: this.$t('stakinglist.ipttraditionalchinese'), trigger: 'blur' },
    descZh:{ required: false, message: this.$t('stakinglist.iptsimplifieddescription'), trigger: 'blur' },
    descEn:{ required: false, message: this.$t('stakinglist.iptexplanationinEnglish'),  trigger: 'blur' },
    minTime:{ required: true, 
     pattern: /^\d+(\.\d+)?$/,
    message: this.$t('stakinglist.iptminimumpledge'), trigger: 'blur' 
    },
    maxTime:{ required: true,
     pattern:/^\d+(\.\d+)?$/,
     message: this.$t('stakinglist.iptmaximumpledge'), trigger: 'blur' 
     },
    maxAll:
    { required: true,
     pattern:/^\d+(\.\d+)?$/,
     message: this.$t('stakinglist.iptpledgeatmost'), trigger: 'blur' },
 }
  }
},
methods:{
  changeType(event){
  if(event == 2){
    this.disabled.disabledhouqi = false
    this.disabled.disabledsiqi = true
  }else{
    this.disabled.disabledhouqi = true
    this.disabled.disabledsiqi = false
  }
  },
  getstakingdatalist(){
this.loading=true
getUserRequest(this.select, '/staking/list').then(res=>{
  let stakingList = res.data
  if(stakingList.code == 200){
  this.stakingListdata = stakingList.data;
  for(let i=0;i<this.stakingListdata.length;i++){
    this.stakingListdata[i].minTime = this.stakingListdata[i].minTime / this.million;
    this.stakingListdata[i].maxTime = this.stakingListdata[i].maxTime / this.million;
    this.stakingListdata[i].maxAll = this.stakingListdata[i].maxAll / this.million;
  }
  }else{
	this.$message({
				message: stakingList.message,
				type: "error"
				})
  }
  this.loading=false;
  })
  },
  getstakingSubmit(){
    if(this.select.crypto){
      this.getstakingdatalist()
    }else{
      this.$message({
				message:this.$t('stakinglist.iptcoin'),
				type: "error"
				})
      }
  },
  getstakingRefresh(){
this.getstakingdatalist()

  },
  // 新增
  getnewlyadded(){
  this.upnewtitle = this.$t('publicbtn.newlyadded')
  this.getnewlyadd=true;
  this.getnewlyaddapi=true; //new
  this.getnuplyaddapi=false; //up
  },
  // 科学计数法转化数组
     c(param) {
            let strParam = String(param)
            let flag = /e/.test(strParam)
            if (!flag) return param
            // 指数符号 true: 正，false: 负
            let sysbol = true
            if (/e-/.test(strParam)) {
              sysbol = false
            }
            // 指数
            let index = Number(strParam.match(/\d+$/)[0])
            // 基数
            let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')
            if (sysbol) {
              return basis.padEnd(index + 1, 0)
            } else {
              return basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
            }
      },
  // 修改
  updatastking(data){
    this.changeType(data.type)
    this.upnewtitle = this.$t('publicbtn.modifyinformation');
    this.getupdatanewdata = JSON.parse(JSON.stringify(data));
    this.getupdatanewdata.minTime = this.c(this.getupdatanewdata.minTime);
    this.getnewlyadd = true;
    this.getnewlyaddapi = false; //new
    this.getnuplyaddapi = true; //up
  },
  // 修改and提交
  usernewupSubmit(getupdatanewdata){

 this.$refs[getupdatanewdata].validate((valid) => {
   if(valid){
     let updataandnewdata= JSON.parse(JSON.stringify(this.getupdatanewdata))
     updataandnewdata.minTime = parseInt((Number(this.getupdatanewdata.minTime)+0.0000000001)*this.million)
     updataandnewdata.maxTime = parseInt((Number(this.getupdatanewdata.maxTime)+0.0000000001)*this.million)
     updataandnewdata.maxAll = parseInt((Number(this.getupdatanewdata.maxAll)+0.0000000001)*this.million)
        if(this.getnewlyaddapi){
        postUserRequest(updataandnewdata,'/staking/save').then(res=>{
            let newdata = res.data;
          if(newdata.code==200){
            this.getstakingdatalist()
          }else{
            this.$message({
              message: newdata.message,
              type: "error"
              })
          }
            this.getnewlyadd=false;
        }).catch(e=>{
            this.$message({
                message: newdata.message,
                type: "error"
                })
            this.getnewlyadd=false;
        })

    }else if(this.getnuplyaddapi){
   postUserRequest(updataandnewdata,'/staking/update').then(res=>{
          let updata = res.data;
          if(updata.code==200){
          this.getstakingdatalist()
          }else{
              this.$message({
                message: updata.message,
                type: "error"
                })
          }
          this.getnewlyadd=false;
        })
    }
    this.getupdatanewdata ={}

   }

 })

  },
  // 关闭
  usernewupSubmitReset(){
  this.getupdatanewdata={}
  this.getnewlyadd=false;
  },
  // 删除
  delectStkingbtn(id){
       this.$alert(this.$t('stakinglist.delete'),this.$t('stakinglist.updelete'), {
          confirmButtonText: this.$t('publicbtn.determine'), 
          distinguishCancelAndClose:true,
          callback: action => {
            if(action=='confirm'){
               this.delectStking(id)
            }
          },
        });
        
    
  },

  delectStking(id){
    var del={
      id:id
    }
 getUserRequest(del,`/staking/del`).then(res=>{
             console.log(res)
             if(res.data.code ==200){
          this.getstakingdatalist()
             }else{
              this.$message({
                message: res.data.message,
                type: "success"
                })
             }
           })
   
},
// 导入

  // excel表上传
  /** 导入按钮操作 **/
 handleChange(file, fileList) { //excel文件改变
     this.fileTemp = file.raw
      if (this.fileTemp) {
        if ((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp
            .type == 'application/vnd.ms-excel')) {
          this.importExcel(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message:  this.$t('bulletframe.importtile')
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: this.$t('bulletframe.importuptile')
        })
      }
 }, 
 importExcel(obj) {
    let _this = this;
    // 通过DOM取文件数据
    this.file = obj
    var rABS = false; //是否将文件读取为二进制字符串
    var f = this.file;
    var reader = new FileReader();
    FileReader.prototype.readAsBinaryString = function(f) {
      var binary = "";
      var rABS = false; //是否将文件读取为二进制字符串
      var pt = this;
      var wb; //读取完成的数据
      var outdata;
      var reader = new FileReader();
      reader.onload = function(e) {
        var bytes = new Uint8Array(reader.result);
        var length = bytes.byteLength;
        for (var i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        var XLSX = require('xlsx');
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
            type: 'base64'
          });
        } else {
          wb = XLSX.read(binary, {
            type: 'binary'
          });
        }
        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
        _this.da = [...outdata]
        //这里 处理导入的excel数据
//  return
  let das = new Promise(function(resolve, reject){
        _this.da.map(v => {
         v['name'] = v[_this.$t('field.nametw')]
         delete v[_this.$t('field.nametw')];

         v['crypto'] = v['Coin']
         delete v['Coin'];

         v['type'] = v[_this.$t('stakinglist.type')] == _this.$t('stakinglist.current')?1:2
         delete v[_this.$t('stakinglist.type')];
           
          v['rate'] = v[_this.$t('stakinglist.interestrate')]
         delete v[_this.$t('stakinglist.interestrate')];
           
          v['sort'] = v[_this.$t('field.sort')]
         delete v[_this.$t('field.sort')]
         
         v['cycle'] = v[_this.$t('stakinglist.payoutperiod')]
         delete v[_this.$t('stakinglist.payoutperiod')]

         v['lockDay'] = v[_this.$t('stakinglist.nvestmentperiod')]
         delete v[_this.$t('stakinglist.nvestmentperiod')]
        
         v['unlockDay'] = v[_this.$t('stakinglist.unlockingperiod')]
         delete v[_this.$t('stakinglist.unlockingperiod')]
  
         v['descTc'] = v[_this.$t('stakinglist.traditionalchinese')]
         delete v[_this.$t('stakinglist.traditionalchinese')]

        v['descZh'] = v[_this.$t('stakinglist.simplifieddescription')]
                delete v[_this.$t('stakinglist.simplifieddescription')]

        v['descEn'] = v[_this.$t('stakinglist.explanationinEnglish')]
                delete v[_this.$t('stakinglist.explanationinEnglish')]

        v['minTime'] = v[_this.$t('stakinglist.minimumpledge')]*_this.million
                delete v[_this.$t('stakinglist.minimumpledge')]

        v['maxTime'] = v[_this.$t('stakinglist.maximumpledge')]*_this.million
                delete v[_this.$t('stakinglist.maximumpledge')]


        v['maxAll'] = v[_this.$t('stakinglist.pledgeatmost')]*_this.million
                delete v[_this.$t('stakinglist.pledgeatmost')]


          })
         resolve(_this.da)
           })
           das.then(res=>{
            postUserRequest(res,'/staking/saveList').then(res=>{
          let newdata = res.data;
         

          if(newdata.code==200){
             _this.$message({
                message: newdata.message,
                type: "error"
                })
          _this.getstakingdatalist()
          }else{
              _this.$message({
                message: newdata.message,
                type: "error"
                })
          }
           
             
           })
           })
          
      }
      
        
      reader.readAsArrayBuffer(f);
    }

    if (rABS) {
      reader.readAsArrayBuffer(f);
    } else {
      reader.readAsBinaryString(f);
    }
 },


},
mounted(){
this.getstakingdatalist()


//   var timestamp =new Date().getTime();
//   let Message ='recvWindow='+60000+'&'+'timestamp='+timestamp;
//   let key = 'o1q1wOWycXJuqWdWgX4ielEBTqe8a3YdKPvgds0GfpHWj6jkEyuNtJd67pAmcdsu';
//   let hash = Cryptojs.HmacSHA256(Message, key).toString();
// console.log(timestamp,hash,this)
}
}
</script>

<style scouped>
 .userUpdateMoney {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 9;
}
.userUpdateForm {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
  padding: 30px;
  background: #fff;
  box-shadow: 0px 0px 3px #888;
}
.userUpdateMoney h2 {
  text-align: center;
  font-size: 18px;
}

</style>